<template>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      show-footer
      width="40%"
      @ok="handleSubmit"
    >
      <template #title>
        {{ isUpdate ? '编辑' : '新增' }}
      </template>
      <template #footer>
        <a-button @click="closeModal" :loading="btnLoading">取消</a-button>
        <a-button
          type="primary"
          @click="handleSubmit(false)"
          :loading="btnLoading"
          >保存</a-button
        >
      </template>
      <BasicForm @register="registerForm">
        <template #menus>
          <Tree v-if="menus.length" ref="menuTree" checkStrictly checkable :tree-data="menus" st v-model:checked-keys="selectedKeys" defaultExpandAll :fieldNames="{ title: 'name', key: 'id'}" @check="handleMenuChange"/>
        </template>
      </BasicForm>  
    </BasicModal>
  </template>
  <script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { Tree } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useThrottleFn } from '@vueuse/core';
  import { defHttp } from '@/utils/http/axios';
  import { listToTree } from '@/utils/helper/treeHelper';
  const emit = defineEmits(['success', 'register']);
  let isUpdate = ref(true);
  const btnLoading = ref(true);
  const { createMessage } = useMessage();
  const [
    registerForm,
    { resetFields, getFieldsValue, setFieldsValue, validate },
  ] = useForm({
    labelWidth: 100,
    schemas: [
      {
        field: 'id',
        component: 'Input',
        label: 'id',
        show: false,
      },
      {
        label: '角色名',
        field: 'name',
        component: 'Input',
        required: true,
      },
      {
        label: '描述',
        field: 'description',
        component: 'InputTextArea',
      },
      {
        label: '菜单权限',
        field: 'menuList',
        component: 'Input',
        slot: 'menus',
      },
    ],
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  const menus = ref([]);
  const menuTree = ref(null);
  const selectedKeys = ref<{ checked: string[] }>({ checked: [] });
  function getAllMenus() {
    defHttp.get({ url: '/admin/main/menuListAll' }).then((res) => {
      menus.value = listToTree(res, { pid: 'parentId' });

    }); 
  }
  function getRoleMenus(roleId: number) {
    defHttp.get({ url: `/admin/main/menuListByRole/${roleId}` }).then((res) => {
      console.log(res.map((item) => item.id));
      selectedKeys.value = res.map((item) => item.id);
      setFieldsValue({ menuList: selectedKeys.value });
    });
  }
  function handleMenuChange() {
    console.log(selectedKeys.value), 'dada';
    setFieldsValue({ menuList: selectedKeys.value.checked });
  }
  const [registerModal, { closeModal, changeLoading }] =
  useModalInner(async (data) => {
      resetFields();
      debugger
      changeLoading(true);
      btnLoading.value = true;
      isUpdate.value =!!data?.isUpdate;
      getAllMenus();
      if (isUpdate.value) {
        setFieldsValue({ ...data.record });
        getRoleMenus(data.record.id);
      } 
      changeLoading(false);
      btnLoading.value = false;
    });
  const handleSubmit = useThrottleFn(doSubmit, 1000);
  async function doSubmit(hasNext: boolean) {
    try {
      changeLoading(true);
      btnLoading.value = true;
      const values = await validate();
      if (isUpdate.value) {
        const res = await defHttp.post({ url: '/admin/role/update', data: values });
        createMessage.success(res);
      } else {
        const res = await defHttp.post({ url: '/admin/role/save', data: values });
        createMessage.success(res);
      }
      emit('success');
      closeModal();
    } finally {
      btnLoading.value = false;
      changeLoading(false);
    }
  }
  </script>
  